<template>
  <div class="testTop">
     
    <!-- 头部 -->
    <div class="tops">
      <span class="test">考试管理</span>
      <el-button
        v-if="isButton(30)"
        style="backgroundcolor: #409eff; font-size: 12px"
        type="primary"
        @click="toAdd"
        >创建考试</el-button
      >
    </div>
    <!-- 头部 -->
    <div class="from">
      <el-row>
        <el-col :span="3"
          ><div class="grid-content ep-bg-purple" />
          <el-form-item label="关键字" style="font-size: 14px">
            <el-input v-model="params.key" placeholder="考试名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <div class="grid-content ep-bg-purple-light" />
          <el-form-item
            label="创建人"
            style="font-size: 14px; margin-left: 10px"
          >
            <el-input v-model="params.admin" placeholder="创建人" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="16" style="margin-top: -20px" class="elc"
          ><div class="grid-content ep-bg-purple" />
          <el-checkbox
            v-model="params.ismy"
            true-label="1"
            false-label="0"
            style="padding: 0px 5px 0px 10px"
            size="large"
            @change="change"
          />
          <span>我创建的</span>
          <span style="padding: 0px 10px 0px 10px">开放时间</span>
          <el-radio-group v-model="radio">
            <el-radio :label="1" value="1">永久开放</el-radio>
            <el-radio :label="2" value="2">部分时段</el-radio>
          </el-radio-group>
          <div class="demo-date-picker" style="">
            <el-date-picker
              v-model="value1"
              type="datetimerange"
              :shortcuts="shortcuts"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :readonly="flag == false"
              style="width: 250px"
              format="YYYY-MM-DD"
              @change="changeRi"
            />
          </div>
          <span style="padding: 0px 5px 0px 10px">状态</span>
          <el-select
            v-model="region"
            placeholder="请选择"
            @change="selectDoctor"
            style="width: 100px"
          >
            <el-option label="所有" value="0" />
            <el-option label="已发布" value="1" />
            <el-option label="未发布" value="2" />
          </el-select>
          <el-button
            style="font-size: 13px"
            type="primary"
            @click="sel"
            class="sel"
            >查询</el-button
          >
        </el-col>
      </el-row>
    </div>
    <!-- 中间按钮 -->
    <div class="button" v-if="num">
      <el-button type="danger" style="font-size: 12px" @click="deletes"
        >批量删除</el-button
      >
      <el-button
        type="primary"
        style="font-size: 12px"
        @click="UpdateState(1, 1)"
        >发布考试</el-button
      >
      <el-button
        type="success"
        style="font-size: 12px"
        @click="UpdateState(2, 1)"
        >取消发布</el-button
      >
    </div>
    <!-- 表格 -->
    <div class="tab">
      <el-table
        ref="multipleTableRef"
        v-loading="fullscreenLoading"
        :data="testInfo"
        style="width: 100%"
        :header-cell-style="{ backgroundColor: '#fafafa' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="考试名称" width="200">
          <template #default="scope">
            <a
              class="stu"
              style="font-size: 13px"
              @click="bounced(scope.row)"
              >{{ scope.row.title }}</a
            >
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <a class="stus" v-if="scope.row.state == 1" style="font-size: 13px"
              >已发布</a
            >
            <a
              class="del"
              v-if="scope.row.state == 2"
              @click="UpdateState(1, scope.row.id)"
              style="font-size: 13px"
              >未发布</a
            >
          </template>
        </el-table-column>
        <el-table-column
          property="scores"
          label="总分"
          width="120"
          show-overflow-tooltip
        />
        <el-table-column
          property="pastscores"
          label="通过分数"
          show-overflow-tooltip
        />
        <el-table-column
          property="studentcounts"
          label="考试人数"
          show-overflow-tooltip
        />
        <el-table-column
          property="passCounts"
          label="通过人数"
          show-overflow-tooltip
        />
        <el-table-column property="" label="开放时间" width="170">
          <template #default="scope">
            {{
              scope.row.begintime === null
                ? "不限"
                : scope.row.begintime.substr(0, 16) +
                  "至" +
                  scope.row.endtime.substr(0, 16)
            }}
          </template>
        </el-table-column>
        <el-table-column property="admin" label="创建人" />
        <el-table-column property="addtime" label="更新时间" width="130">
          <template #default="scope">
            {{ scope.row.addtime.substr(0, 16) }}
          </template></el-table-column
        >
        <el-table-column fixed="right" label="操作" width="170">
          <template #default="scope">
            <div>
              <a class="stu" @click="stu(scope.row)">学生</a> |
              <a class="stu" @click="visible(scope.row)">可见</a> |
              <a class="stu" @click="marking(scope.row)">阅卷老师</a>
            </div>
            <div>
              <a
                class="stu"
                @click="
                  toAnalyze(
                    scope.row.id,
                    scope.row.studentcounts,
                    scope.row.isread,
                    scope.row
                  )
                "
                >分析</a
              >
              | <a class="stu" @click="update(scope.row)" v-if="isButton(65)">编辑</a> |
              <a class="del" @click="del(scope.row.id)" v-if="isButton(66)">删除</a>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="current">
        <el-pagination
          v-model:currentPage="params.page"
          v-model:page-size="params.psize"
          :page-sizes="[20, 50, 100, 200]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="counts"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <Student :is="is" @iss="iss" :stu="stus" :testid="id"></Student>
    <Parper :isPar="isPar" @isPars="isPars" :id="id" :title="title" :isTest="isTest"></Parper>
  </div>
</template>

<script lang='ts' setup>
import moment from "moment";
import { onMounted, reactive, ref, toRefs, watchEffect } from "vue";
import { useRouter } from "vue-router";
import { ElTable, ElMessage, ElMessageBox } from "element-plus";
// 引入封装的接口
import { TestList, TestDel, TestDels, TestState } from "../../apis/test/test";
// 引入封装的组件
import Student from "../../components/test/student.vue";
import Parper from "../../components/test/Paper.vue";
// 引入封装隐藏按钮的方法
import {isButton} from "../../utils/isButton";

// 数据
const data: any = reactive({
  // 赋值的数组
  testInfo: [],
  // 掉列表接口参数
  params: {
    page: 1,
    psize: 20,
    ismy: 0,
    key: "",
    admin: "",
    state: 0,
    begindate:'',
    enddate:''
  },
  is: false,
  isPar: false,
  stus: "",
  // 学生id
  id: 0,
  title: "",
  isTest:true,

});
const {isTest, params, testInfo, is, stus, isPar, id, title } = toRefs(data);
watchEffect(() => {
  if (params.value.admin !== "") {
    params.value.ismy = 0;
  }
});
const change = (val: string) => {
  if (val === "1") {
    params.value.admin = "";
  }
};
// 单选框
const radio = ref(1);
const flag = ref(false);
watchEffect(() => {
  radio.value === 2 ? (flag.value = true) : (flag.value = false);
});
// 日期
const value1 = ref("");
const shortcuts = [
  {
    text: "今天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: "最近一周",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: "最近一个月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];
const changeRi=(e:any)=>{
  // console.log(e)
  params.value.begindate = moment(e[0]).format('YYYY-MM-DD');
  params.value.enddate = moment(e[1]).format('YYYY-MM-DD');
  console.log(params.value)
}
// 下拉菜单
const region = ref("");
// 获取下拉菜单的值
const selectDoctor = (val: any) => {
  params.value.state = val;
  list();
};
// 表格
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
// 三个按钮
const num = ref(false);
// 批删
const DelIds = reactive({
  Ids: [],
});
const { Ids }: any = toRefs(DelIds);
// 批删方法
const dels = async () => {
  const res: any = await TestDels(Ids.value);
  if (res.errCode == "10000") {
    ElMessage({
      message: "批删成功",
      type: "success",
    });
    fullscreenLoading.value = true;
    setTimeout(() => {
      fullscreenLoading.value = false;
      list();
    }, 600);
  } else {
    ElMessage({
      message: res.errMsg,
      type: "error",
    });
  }
};
const deletes = async () => {
  const conf = await ElMessageBox.confirm(
    "此操作将永久删除该文件, 是否继续?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).catch(() => {
    ElMessage.error("已取消删除");
  });
  if (conf) dels();
};
const handleSelectionChange = (val: any) => {
  val == "" ? (num.value = false) : (num.value = true);
  Ids.value = val.map((item: any) => item.id);
};
// 列表接口
const list = async () => {
  fullscreenLoading.value = true;
  const res: any = await TestList(params.value);
  // console.log(res)
  if (res.errCode === 10000) {
    testInfo.value = res.data.list;
    counts.value = res.data.counts;
  } else {
    ElMessage.error(res.errMsg);
  }
  fullscreenLoading.value = false;
};
const fullscreenLoading = ref(true);
onMounted(() => {
  list();
  setTimeout(() => {
    fullscreenLoading.value = false;
  }, 600);
});
// 点击分析,根据传过来的参数来判断能否进入分析页面
const toAnalyze = (testid: any, studentcounts: any, isread: any,row:any) => {
  if (studentcounts == 0) {
    ElMessage({
      message: "没有学生考试",
      type: "error",
    });
  }else if(row.incomplete!=0){
     ElMessage({
      message: "该试卷未判完",
      type: "error",
    });
  } 
  else {
    router.push({ path: "/Analyse", query: { testid: testid } });
  }
};


// 总条数
const counts = ref(0);
const handleSizeChange = (val: number) => {
  params.value.psize = val;
  fullscreenLoading.value = true;
  setTimeout(() => {
    fullscreenLoading.value = false;
    list();
  }, 600);
};
const handleCurrentChange = (val: number) => {
  params.value.page = val;
  fullscreenLoading.value = true;
  setTimeout(() => {
    fullscreenLoading.value = false;
    list();
  }, 600);
};
// 查询
const sel = () => {
  list();
};
// 删除定义的方法
const dell = async (ids: any) => {
  const res: any = await TestDel(ids);
  if (res.errCode == "10000") {
    ElMessage({
      message: "删除成功",
      type: "success",
    });
    fullscreenLoading.value = true;
    setTimeout(() => {
      fullscreenLoading.value = false;
      list();
    }, 600);
  } else {
    ElMessage.error(res.errMsg);
  }
};
// 删除
const del = (ids: number) => {
  ElMessageBox.confirm("确定要删除该考试吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      dell(ids);
    })
    .catch(() => {
      ElMessage.error("已取消删除");
    });
};
//修改发布状态
let arrId: any = [];
const UpdateState = async (state: number, id: number) => {
  arrId.push(id);
  const conf = await ElMessageBox.confirm(
    "此操作将修改选中的考试状态, 是否继续?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).catch(() => {});

  if (!conf) return false;

  if (id === 1 || id === 2) {
    let data = {
      state,
      ids: [...DelIds.Ids],
    };
    const res: any = await TestState(data).catch((res) => {});
    if (res.errCode == "10000") {
      ElMessage({
        message: "修改成功",
        type: "success",
      });
      list();
    } else {
      ElMessage.error(res.errMsg);
    }
  }
  if (id) {
    let data = {
      state,
      ids: arrId,
    };
    const res: any = await TestState(data).catch((res) => {});
    if (res.errCode == "10000") {
      ElMessage({
        message: "修改成功",
        type: "success",
      });
      list();
    } else {
      ElMessage.error(res.errMsg);
    }
  }
};
// 接受子传来的值
const iss = (e: any) => {
  is.value = e;
};
// 弹出学生对话框
const stu = (row: any) => {
  is.value = true;
  stus.value = "学生";
  id.value = row.id;
};
// 弹出可见对话框
const visible = (row: any) => {
  is.value = true;
  stus.value = "可见";
  id.value = row.id;
};
// 弹出可见对话框
const marking = (row: any) => {
  is.value = true;
  stus.value = "阅卷老师";
  id.value = row.id;
};
// 跳转到添加考试
const router = useRouter();
const toAdd = () => {
  router.push("/testadd/1");
};
// 子传父
const isPars = (e: any) => {
  isPar.value = e;
};
// 试卷弹框
const bounced = (row: any) => {
  isButton(29) ? isPar.value = true : isPar.value = false
  id.value = row.id;
  title.value = row.title;
};
// 跳到编辑
const update = (row:any) => {
  row.studentcounts > 0 ? ElMessage.error('本场考试已有学生参加，不可编辑') : router.push(`/TestAdd/${row.id}`);
};
</script>
<style scoped>
@import url("../../static/css/test/test.css");
</style>